<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>教师作业查看管理</title>
    <link rel="stylesheet" href="/static/css/layui.css">
</head>

<body>

    <!-- 主体部分 -->
    <div class="layui-card">
        <div class="layui-card-body">

            <div class="layui-form">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <div class="layui-input-inline">
                            <input type="text" id="hnumber" name="hnumber" placeholder="作业编号" autocomplete="off"
                                class="layui-input">
                        </div>
                        <div class="layui-input-inline">
                            <input type="text" id="class_id" name="class_id" placeholder="上课班级" autocomplete="off"
                                class="layui-input">
                        </div>
                        <div class="layui-input-inline">
                            <input type="text" id="class_id1" name="class_id1" placeholder="自然班级" autocomplete="off"
                                class="layui-input">
                        </div>
                        <div class="layui-input-inline">
                            <input type="text" id="stu_id" name="stu_id" placeholder="学生学号" autocomplete="off"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button id="btn_search" class="layui-btn layui-icon  layui-icon-search" data-type="search">查询
                        </button>
                    </div>
                    <div class="layui-inline">
                        <button id="btn_refresh" class="layui-btn layui-icon  layui-icon-refresh" data-type="search">重置
                        </button>
                    </div>
                    <div class="layui-inline">
                        <button id="export-button" class="layui-btn layui-icon  layui-icon-refresh" data-type="search">
                            表格当前页导出到Excel
                        </button>
                    </div>
                </div>

            </div>

            <table id="manage_table" lay-filter="manage_table"></table>
        </div>
    </div>

    <!--文本作业操作按钮-->
    <script type="text/html" id="text_operation">
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="view_text">查看文本</a>
    </script>

    <!--其他操作-->
    <script type="text/html" id="other_operation">

    </script>


    <!-- javascript 脚本 -->
    <script src="/static/layui.js"></script>
    <script src="/static/jquery-3.6.0.min.js"></script>
    <script src="/static/jquery.table2excel.js"></script>
    <script>
        layui.use(['layer', 'form', 'table'], function () {
            var table = layui.table;

            var
                $ = layui.jquery,
                table = layui.table,
                form = layui.form,
                layer = layui.layer;

            var currentRow = {},
                currentOpt = "",
                testUrl = "/uploadhomework/test",
                listUrl = "/uploadhomework/teacher_list",  // 教师专用API
                layerIndex = 0;

            // 更新文本作业成绩的函数
            window.updateTextGrade = function (uploadId, grade) {
                if (grade === '' || grade < 0 || grade > 100) {
                    layer.msg('评分必须是0-100之间的数字', { icon: 2 });
                    return;
                }

                $.ajax({
                    url: '/uploadhomework/update_text_grade',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        upload_id: uploadId,
                        grade: parseInt(grade)
                    }),
                    success: function (response) {
                        if (response.success) {
                            layer.msg('评分更新成功', { icon: 1 });
                            table.reload('manage_table');
                        } else {
                            layer.msg('评分更新失败: ' + response.message, { icon: 2 });
                        }
                    },
                    error: function () {
                        layer.msg('网络错误', { icon: 2 });
                    }
                });
            };

            $(function () {
                // 查询按钮
                $("#btn_search").on("click", function () {
                    table.reload('manage_table', {
                        where: {
                            hnumber: $("#hnumber").val()
                            , bigsclass: $("#class_id").val()
                            , class_id: $("#class_id1").val()
                            , stu_id: $("#stu_id").val()

                        }
                        , page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    });
                });
                $("#btn_refresh").on("click", function () {
                    initTable();
                });
                initTable();
            });

            function initTable() {
                // 初始化列表(表格)
                table.render({
                    elem: '#manage_table'
                    , url: listUrl //数据接口
                    , method: "GET"
                    , request: {
                        pageName: 'pageIndex',
                        limitName: 'pageSize'
                    }
                    , page: {
                        layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],     // 自定义分页布局
                        curr: 1,      // 设置默认起始页1
                        groups: 10,   //只显示10个连续页码,就是说显示10个可见页其他的省略
                        first: false, // 不显示首页
                        last: false   // 不显示尾页
                    }

                    , limits: [10, 20, 30, 40, 50, 1000000]
                    , toolbar: '#tableToolBar'
                    , defaultToolbar: []
                    , cellMinWidth: 100
                    , cols: [
                        [ //表头

                            { field: 'sid', title: '学生学号', align: 'center', width: 150 }
                            , { field: 'sname', title: '学生姓名', align: 'center', width: 100 }
                            , { field: 'sclass2', title: '上课班级', align: 'center' }
                            , { field: 'sclass', title: '自然班级', align: 'center', width: 100 }
                            , { field: 'hnumber', title: '作业编号', align: 'center' }
                            , {
                                field: 'submission_type', title: '提交类型', align: 'center', width: 100, templet: function (d) {
                                    return d.submission_type === 'text' ? '<span style="color: #01AAED;">文本</span>' : '<span style="color: #FF5722;">代码</span>';
                                }
                            }
                            , { field: 'htime', title: '提交时间', align: 'center' }
                            , {
                                field: 'grade', title: '成绩', align: 'center', width: 140, templet: function (d) {
                                    if (d.submission_type === 'text') {
                                        // 文本作业显示可编辑的成绩输入框
                                        var grade = d.grade === "等待评分" ? "" : d.grade;
                                        return '<div style="display: flex; align-items: center; justify-content: center;">' +
                                               '<input type="number" class="layui-input grade-input" style="width:70px; height:28px; font-size:12px;" ' +
                                               'value="' + grade + '" min="0" max="100" data-id="' + d.ID + '" ' +
                                               'placeholder="分数" onchange="updateTextGrade(' + d.ID + ', this.value)">' +
                                               '<span style="margin-left: 5px; font-size: 12px;">分</span>' +
                                               '</div>';
                                    } else {
                                        // 代码作业显示普通成绩
                                        return d.grade === "等待评分" ? '<span style="color:#999;">等待评分</span>' : '<span style="color:#5FB878;">' + d.grade + '分</span>';
                                    }
                                }
                            }
                            , { field: 'is_copy', title: '抄袭检测结果', align: 'center' }
                            , {
                                title: '操作', align: 'center', width: 140, templet: function (d) {
                                    if (d.submission_type === 'text') {
                                        return '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="view_text">查看文本</a>';
                                    } else {
                                        return '<a class="layui-btn layui-btn-xs" lay-event="test">测试</a>';
                                    }
                                }
                            }
                        ]
                    ],
                    parseData: function (res) { //res 即为原始返回的数据
                        console.log(res)
                        return {
                            "code": res.code == 200 ? 0 : res.code, //解析接口状态
                            "msg": res.code == 200 ? "" : res.msg, //解析提示文本
                            "count": res.count, //解析数据长度
                            "data": res.data //解析数据列表
                        };
                    }
                });
                table.on('tool(manage_table)', function (obj) {
                    if (obj.event == 'test') {
                        currentRow = {};
                        if (obj.data.homeworkpath == null) {
                            alert("作业未提交")
                        } else {
                            $.ajax({
                                type: 'POST', //请求方式
                                url: testUrl, //请求接口地址
                                contentType: 'application/json;charset=utf-8',
                                dataType: 'json',
                                data: JSON.stringify(obj.data), //传送数据
                                success: function (result) { //针对请求结果进行处理
                                    if (result.code === 0) {
                                        alert("你得了" + result.msg + "分");
                                        layer.msg("修改成功！", { time: 500 });
                                        table.reload('manage_table');

                                        document.getElementById("layer_form1").style.visibility = 'hidden'
                                    } else if (result.code === 2) {
                                        alert(result.msg);
                                        layer.msg(result.msg);
                                    } else {
                                        layer.msg("添加失败!");
                                    }
                                }
                            });
                        }
                    } else if (obj.event == 'view_text') {
                        // 查看文本作业内容
                        $.ajax({
                            type: 'GET',
                            url: '/homework/view_text_homework/' + obj.data.ID,
                            success: function (result) {
                                if (result.code === 0) {
                                    var data = result.data;

                                    // 创建安全的DOM元素，防止XSS攻击
                                    var contentDiv = $('<div>').addClass('text-homework-content').css({
                                        'padding': '20px'
                                    });

                                    var titleH3 = $('<h3>').text('作业标题：' + data.homework_title);
                                    var studentP = $('<p>').html('<strong>学生：</strong>' + $('<span>').text(data.student_name + ' (' + data.student_id + ')').html());
                                    var timeP = $('<p>').html('<strong>提交时间：</strong>' + $('<span>').text(data.submit_time).html());
                                    var hr = $('<hr>');
                                    var contentH4 = $('<h4>').text('作业内容：');

                                    var textDiv = $('<div>').css({
                                        'background-color': '#f5f5f5',
                                        'padding': '15px',
                                        'border-radius': '5px',
                                        'max-height': '400px',
                                        'overflow-y': 'auto'
                                    });

                                    var textPre = $('<pre>').css({
                                        'white-space': 'pre-wrap',
                                        'word-wrap': 'break-word'
                                    }).text(data.text_content);

                                    textDiv.append(textPre);
                                    contentDiv.append(titleH3, studentP, timeP, hr, contentH4, textDiv);

                                    var content = contentDiv[0].outerHTML;

                                    layer.open({
                                        title: '查看文本作业',
                                        type: 1,
                                        area: ['800px', '600px'],
                                        content: content,
                                        shadeClose: true
                                    });
                                } else {
                                    layer.msg(result.message || '查看失败', { icon: 2 });
                                }
                            },
                            error: function () {
                                layer.msg('网络错误', { icon: 2 });
                            }
                        });
                    }
                });
            }

            // 给按钮绑定点击事件
            $("#export-button").click(function () {
                // 获取表格数据
                var data = table.cache['manage_table'];
                // 创建一个 HTML 表格字符串
                var tableHtml = '<table>';
                tableHtml += '<thead>';
                tableHtml += '<tr>';
                // 添加表头
                tableHtml += '<th>教学班级</th>';
                tableHtml += '<th>班级</th>';
                tableHtml += '<th>学号</th>';
                tableHtml += '<th>姓名</th>';
                tableHtml += '<th>作业编号</th>';
                tableHtml += '<th>提交类型</th>';
                tableHtml += '<th>成绩</th>';
                tableHtml += '<th>抄袭结果</th>';
                // 添加更多表头列...
                tableHtml += '</tr>';
                tableHtml += '</thead>';
                tableHtml += '<tbody>';
                // 添加数据行
                for (var i = 0; i < data.length; i++) {
                    console.log(data[i])
                    tableHtml += '<tr>';
                    tableHtml += '<td>' + data[i].sclass2 + '</td>';
                    tableHtml += '<td>' + data[i].sclass + '</td>';
                    tableHtml += '<td>' + data[i].sid + '</td>';
                    tableHtml += '<td>' + data[i].sname + '</td>';
                    tableHtml += '<td>' + data[i].hnumber + '</td>';
                    tableHtml += '<td>' + (data[i].submission_type === 'text' ? '文本' : '代码') + '</td>';
                    tableHtml += '<td>' + data[i].grade + '</td>';
                    tableHtml += '<td>' + data[i].is_copy + '</td>';
                    // 添加更多数据列...
                    tableHtml += '</tr>';
                }
                tableHtml += '</tbody>';
                tableHtml += '</table>';

                // 将 HTML 表格添加到页面中
                var downloadLink = document.createElement('a');
                var blob = new Blob(["\uFEFF" + tableHtml], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                downloadLink.href = URL.createObjectURL(blob);
                var hnumber = $("#hnumber").val()
                var class_id = $("#class_id").val()
                downloadLink.download = hnumber + "-" + class_id + 'teacher-export.xlsx';
                downloadLink.click();
            });
        });
    </script>

</body>

</html>
